import 'dart:developer';

import 'package:edu/constants/app_regex.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/data_fetcher.dart';

class CredentialSettingPageLogic extends ChangeNotifier {
  static const kCredentialEmail = 'email';
  static const kCredentialPhone = 'phone';

  final String credentialType;

  late final textController = TextEditingController();
  late final focusNode = FocusNode();

  late final _emailRegex = RegExp(AppRegex.email);
  late final _phoneRegex = RegExp(AppRegex.phone);

  bool validCredential = false;

  CredentialSettingPageLogic({required this.credentialType});

  String get title {
    switch (credentialType) {
      case kCredentialEmail:
        return AppStrings.email;
      case kCredentialPhone:
        return AppStrings.phone;
      default:
        return '';
    }
  }

  String get inputPreText {
    switch (credentialType) {
      case kCredentialEmail:
        return AppStrings.emailColon;
      case kCredentialPhone:
        return AppStrings.phoneColon;
      default:
        return '';
    }
  }

  TextInputType get inputType {
    switch (credentialType) {
      case kCredentialEmail:
        return TextInputType.emailAddress;
      case kCredentialPhone:
        return TextInputType.phone;
      default:
        return TextInputType.text;
    }
  }

  String get inputHintText {
    switch (credentialType) {
      case kCredentialEmail:
        return AppStrings.emailHintText;
      case kCredentialPhone:
        return AppStrings.phoneHintText;
      default:
        return '';
    }
  }

  bool get _isCredentialEmpty {
    switch (credentialType) {
      case kCredentialEmail:
        return AccountInfo.shared.userProfile?.email?.isEmpty ?? true;
      case kCredentialPhone:
        return AccountInfo.shared.userProfile?.phoneNumber?.isEmpty ?? true;
      default:
        return true;
    }
  }

  String get buttonTitle {
    switch (credentialType) {
      case kCredentialEmail:
        return _isCredentialEmpty
            ? AppStrings.bindEmail
            : AppStrings.changeEmail;
      case kCredentialPhone:
        return _isCredentialEmpty
            ? AppStrings.bindPhone
            : AppStrings.changePhone;
      default:
        return '';
    }
  }

  void init() {
    if (credentialType == kCredentialPhone) {
      textController.text = AccountInfo.shared.userProfile?.phoneNumber ?? '';
    } else if (credentialType == kCredentialEmail) {
      textController.text = AccountInfo.shared.userProfile?.email ?? '';
    }

    validCredential = false;
    textController.addListener(() {
      final credential = textController.text;
      validCredential = (credentialType == kCredentialEmail)
          ? _emailRegex.hasMatch(credential) &&
                (credential != AccountInfo.shared.userProfile?.email)
          : _phoneRegex.hasMatch(credential) &&
                (credential != AccountInfo.shared.userProfile?.phoneNumber);
      notifyListeners();
    });
  }

  Future<bool> changeUserPhoneNumber() async {
    final phoneNumber = textController.text;
    if (_phoneRegex.hasMatch(phoneNumber) == false) {
      return false;
    }

    focusNode.unfocus();
    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.clear,
        dismissOnTap: false,
      );
      final response = await DataFetcher.shared.userApi.changeUserPhoneNumber(
        phoneNumber,
      );
      EasyLoading.dismiss();
      if (response.code == 0 && response.status != null) {
        final status = response.status!;
        if (status.status == 1) {
          EasyLoading.showError(AppStrings.phoneNumberAlreadyUsed);
          return false;
        } else if (status.status == 0) {
          EasyLoading.showSuccess(AppStrings.phoneNumberVerifyCodeSended);
          return true;
        } else {
          EasyLoading.showError(AppStrings.unknownError);
          return false;
        }
      } else {
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
        return false;
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      log('Error: $e');
      return false;
    }
  }

  Future<bool> changeUserEmail() async {
    final email = textController.text;
    if (_emailRegex.hasMatch(email) == false) {
      return false;
    }
    focusNode.unfocus();

    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );
      final response = await DataFetcher.shared.userApi.changeUserEmail(email);
      EasyLoading.dismiss();
      if (response.code == 0 && response.status != null) {
        final status = response.status!;
        if (status.status == 1) {
          EasyLoading.showError(AppStrings.emailAlreadyUsed);
          return false;
        } else if (status.status == 0) {
          EasyLoading.showSuccess(AppStrings.emailVerifyCodeSended);
          return true;
        } else {
          EasyLoading.showError(AppStrings.unknownError);
          return false;
        }
      } else {
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
        return false;
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      log('Error: $e');
      return false;
    }
  }
}
